<template>
    <div class="table">
        <div class="container">
            <el-row justify="end">
                <div class="handle-box">
                    <el-input v-model="select_word" placeholder="输入手机号码" class="handle-input mr10"></el-input>
                    <el-button type="primary" icon="search" @click="search();cur_page = 1">搜索</el-button>
                </div>
            </el-row>
            <el-row justify="end">
                <div class="handle-box">
                  <el-date-picker
                    v-model="dateValue"
                    type="daterange"
                    align="right"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :picker-options="pickerOptions">
                </el-date-picker>
                <el-button type="primary" @click="downExcel()">下载</el-button>
                </div>
            </el-row>
            
            <el-table :data="tableData" border ref="multipleTable" v-loading.fullscreen.lock="fullscreenLoading">
                <el-table-column prop="date" label="日期">
                    <template slot-scope="scope">
                        {{ scope.row.create_time | formatTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="order_id" label="订单编号"></el-table-column>
                <el-table-column prop="nickName" label="微信号"></el-table-column>
                <el-table-column prop="price" label="订单金额">
                     <template slot-scope="scope">
                        {{(scope.row.gross_price/100).toFixed(2)}}
                    </template></el-table-column>
                <el-table-column prop="amount" label="实付金额">
                    <template slot-scope="scope">
                        {{(scope.row.amount/100).toFixed(2)}}
                    </template>
                </el-table-column>
                <el-table-column label="订单状态">
                    <template slot-scope="scope">
                        
                        {{scope.row.status | orderStatus}}
                        <!-- {{type === 1 ? '立即购买':'邀请码'}} -->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>

    </div>
</template>

<script>
import { obtainOrderList ,obtainSearchOrder, obtainOrderExcel} from "@/config/api";
import { zhouUrl , baseUrl} from "@/config/env";  
import { dateRegExp } from "@/config/filter";
import axios from 'axios';
export default {
    name: "basetable",
    data() {
        return {
            tableData: [],
            cur_page: 1,
            // 总条数
            total: 0,
            visible: false,
            is_search: false,
            select_word: '',
            // 全屏loading
            fullscreenLoading: false,
            // 时间value
            dateValue: '',
            // 快捷时间
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                    }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            }
        };
    },
    filters: {
        formatTime(time) {
            return dateRegExp(time - 0, "yyyy-MM-dd");
        },
        formattype(type) {
            let str = "";
            // 0 未使用 1已使用 2已过期
            if (state == 0) {
                str = "未使用";
            }
            if (state == 1) {
                str = "已使用";
            }
            if (state == 2) {
                str = "已过期";
            }
            return str;
        },
        orderStatus (status) {
            let str = '' 
            if (status == 1) {
                str = '未付款'
            }
            if (status == 2) {
                str = '成功'
            }
            if (status == 3) {
                str = '失败'
            }
            return str
        }
    },
    computed: {},
    created() {},
    mounted() {
        this.getData();
    },
    methods: {
        // 获取数据
        async getData() {
            let data = await obtainOrderList(this.cur_page);
            console.log("数据", data);
            this.tableData = data.list;
            this.total = data.total;
        },
        // 分页导航
        handleCurrentChange(val) {
            this.cur_page = val;
           
            if (this.is_search) {
                this.search();
            } else {
                this.getData();
            }
            
        },
        // 学员搜索
        async search() {
            if (!this.select_word) {
                this.cur_page = 1
                this.getData();
                this.is_search = false;
                return false;
            }
            this.is_search = true;
            let phone = this.select_word.replace(/(^\s*)|(\s*$)/g,"")
            if (phone.length != 11) {
                this.$message.error("请输入正确的手机号码");
                return false;
            }
            await obtainSearchOrder(phone, this.cur_page)
                .then( res => { 
                    console.log('订单搜索',res)
                    if (res.status === 200) {
                        this.tableData = res.data
                        this.total = res.total
                    } else {
                        this.$message.error("用户不存在");
                    }
                })
        },
        // 下载表格
        // async downExcel () {
        //     console.log(this.dateValue)
        //     if (this.dateValue && this.dateValue.length) {
        //         const startTime = new Date(this.dateValue[0]).getTime();
        //         const endTime = new Date(this.dateValue[1]).getTime();
        //         const data = await axios({method:'POST',url: baseUrl+'/weapp/order/downOrderExcel',data:{startTime,endTime}})
        //         // const data = await obtainOrderExcel(startTime,endTime);
        //         const blob = new Blob([data.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
        //         const downloadElement = document.createElement('a');
        //         const href = window.URL.createObjectURL(blob); // 创建下载的链接
        //         downloadElement.href = href;
        //         downloadElement.download = '订单管理.xls'; // 下载后文件名
        //         document.body.appendChild(downloadElement);
        //         downloadElement.click(); // 点击下载
        //         document.body.removeChild(downloadElement); // 下载完成移除元素
        //         window.URL.revokeObjectURL(href); // 释放掉blob对象
        //     }
        // },
        async downExcel(){
            if ( !this.dateValue || !this.dateValue.length) {
                this.$message.error("请选择时间");
                return false;
            }
            const startTime = new Date(this.dateValue[0]).getTime();
            const endTime = new Date(this.dateValue[1]).getTime();
            // loadding
            this.fullscreenLoading = true;
            // 下载订单
            const data = await obtainOrderExcel(startTime,endTime);
            if (data && data['data'] && data['data'].length) {
                this.dateValue = '';
                //要导出的json数据
                const jsonData = data['data'];
                //列标题
                let str = `<tr><td>创建时间</td><td>订单ID</td><td>批次ID</td><td>union_id</td><td width="200">学员ID</td><td>微信名称</td><td>学员APP名称</td><td>订单金额</td><td>付款金额</td><td>支付方式</td><td>付款平台</td><td>手机号码（券）</td><td>手机号码来源（券）</td><td>用优惠券的类型</td><td>app登录的手机号码</td></tr>`;
                //循环遍历，每行加入tr标签，每个单元格加td标签
                for(let i = 0 ; i < jsonData.length ; i++ ){
                    str+='<tr>';
                    for(let item in jsonData[i]){
                        //增加\t为了不让表格显示科学计数法或者其他格式
                        str+=`<td>${ jsonData[i][item] + '\t'}</td>`;     
                    }
                    str+='</tr>';
                }
                //Worksheet名
                let worksheet = 'Sheet1'
                let uri = 'data:application/vnd.ms-excel;base64,';
            
                //下载的表格模板数据
                let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
                xmlns:x="urn:schemas-microsoft-com:office:excel" 
                xmlns="http://www.w3.org/TR/REC-html40">
                <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                    <x:Name>${worksheet}</x:Name>
                    <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                    </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                    </head><body><table>${str}</table></body></html>`;
                //下载模板
                window.location.href = uri + this.base64(template);
            };
            this.fullscreenLoading = false;
        },
        base64 (s) { 
            return window.btoa(unescape(encodeURIComponent(s))) 
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.del-dialog-cnt {
    font-size: 16px;
    text-align: center;
}
</style>
